import re
from django import http
from django.contrib.auth import login, logout
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from django_redis import get_redis_connection
from apps.users.models import User
import logging
from utils.response_code import RETCODE
from utils.views import LoginRequiredJSONMixin
import json
from django.contrib.auth.mixins import LoginRequiredMixin

from apps.users import constants
from apps.users.models import Address
from .utils import check_verify_email_token, generate_verify_email_url
from celery_tasks.email_active.tasks import send_verify_email
logger = logging.getLogger('django')

class RegisterView(View):

    def get(self,request):

        return render(request,'register.html')

    def post(self,request):
        """
        1.接收参数
        2.获取参数
        3.验证参数是否齐全
        4.判断用户名是否符合条件
        5.验证密码是否符合条件
        6.验证确认密码是否一致
        7.验证手机号是否正确
        8.验证是否同意协议
        9.创建用户
        10.保存登陆状态
        11.跳转到首页
        """
        # 1.接收参数
        data=request.POST
        # 2.获取参数
        username=data.get('username')
        password=data.get('password')
        password2=data.get('password2')
        mobile=data.get('mobile')
        allow=data.get('allow')
        sms_code=data.get('sms_code')
        # 3.验证参数是否齐全
        if not all([username,password,password2,mobile,allow,sms_code]):
            return http.HttpResponseBadRequest('缺少必须的参数')
        # 4.判断用户名是否符合条件
        if not re.match(r'^[0-9a-zA-Z_]{5,20}$',username):
            return http.HttpResponseBadRequest('用户名不正确')
        # 5.验证密码是否符合条件
        if not re.match(r'^[0-9a-zA-Z]{8,20}$',password):
            return http.HttpResponseBadRequest('密码格式不正确')
        # 6.验证确认密码是否一致
        if password != password2:
            return http.HttpResponseBadRequest('密码不一致')
        # 7.验证手机号是否正确
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return http.HttpResponseBadRequest('手机号格式不正确')
        # 8.验证是否同意协议
        if allow != 'on':
            return http.HttpResponseBadRequest('未同意协议')

        #验证短信验证码
        #连接redis,获取redis的短信验证码,并且比对
        redis_conn=get_redis_connection('code')
        redis_sms_code = redis_conn.get('sms_%s'%mobile)
        if redis_sms_code is None:
            return render(request, 'register.html', {'sms_code_errmsg':'无效的短信验证码'})

        if redis_sms_code.decode() != sms_code:
            return render(request, 'register.html', {'sms_code_errmsg': '输入短信验证码有误'})

        # 9.创建用户
        try:
            user = User.objects.create_user(username=username,
                                        password=password,
                                        mobile=mobile)
        except Exception as e:
            logger.error(e)
            return render(request,'register.html',{'register_errmsg':'创建失败'})
        # 10.保存登陆状态
        login(request,user)
        # 11.跳转到首页
        return redirect(reverse('contents:index'))
        # return http.HttpResponse('注册成功，重定向到首页')

class RegisterUsernameCountView(View):

    def get(self,request,username):
        """
         1.根据用户名查询数量
         2.返回个数信息
        """
        try:
            count = User.objects.filter(username=username).count()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code':RETCODE.DBERR,'errmsg':'数据查询失败'})

        return http.JsonResponse({'code':RETCODE.OK,'msg':'ok','count':count})

class RegisterMobileCountView(View):

    def get(self,request,mobile):
        """
         1.根据用户名查询数量
         2.返回个数信息
        """
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code':RETCODE.DBERR,'errmsg':'数据查询失败'})
        return http.JsonResponse({'code':RETCODE.OK,'msg':'ok','count':count})

class LoginView(View):
    def put(self, request, *args, **kwargs):
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.handle_context_data(**kwargs)



    def get(self,request):

        return render(request,'login.html')

    def post(self,request):
        """
         1.接收参数
         2.获取参数
         3.判断参数是否齐全
         4.判断用户名是否符合要求
         5.判断密码是否符合要求
         6.根据用户名进行查询
         7.根据是否记住密码设置会话有效期
         8.跳转到首页
        """
        # 1.接收参数
        data=request.POST
        #data=json.loads(request.body)
        # 2.获取参数

        username=data.get('username')
        password=data.get('password')
        is_remembered=data.get('remembered')
        # 3.判断参数是否齐全
        if not all([username,password]):

            return http.HttpResponseBadRequest('参数不全')

        # 4.判断用户名是否符合要求
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$',username):
            return http.HttpResponseBadRequest('用户名格式不正确')

        # 5.判断密码是否符合要求
        if not re.match(r'^[0-9A-Za-z]{8,20}$',password):
            return http.HttpResponseBadRequest('密码格式不正确')
        # 6.进行用户名和密码的验证
        from django.contrib.auth import authenticate
        user = authenticate(username=username,password=password)
        if user is None:
            return render(request,'login.html',{'errmsg':'用户名或密码错误'})
        # 7.根据是否记住密码设置会话有效期
        login(request,user)
        if is_remembered != 'on':
            request.session.set_expiry(0)
        # 8.跳转到首页/next页面
        next = request.GET.get('next')
        if next:
            response = redirect(next)

        else:
            response = redirect(reverse('contents:index'))

        response.set_cookie('username',username,max_age=15*24*3600)

        return response

class LogoutView(View):

    def get(self,request):
        #退出登陆
        from django.contrib.auth import logout
        logout(request)

        #清除cookie信息中的username
        response = redirect(reverse('contents:index'))

        response.delete_cookie('username')

        return response



class UserInfoView(LoginRequiredMixin,View):
    """用户中心"""

    def get(self, request):
        info_data = {
            'username': request.user.username,
            'mobile': request.user.mobile,
            'email': request.user.email,
            'email_active': request.user.email_active
        }
        return render(request, 'user_center_info.html',info_data)
        #return JsonResponse({'code':0,'errmsg':'ok','info_data':info_data})

class EmailView(LoginRequiredMixin,View):
        """添加邮箱"""

        def put(self, request):
            """实现添加邮箱逻辑"""
            # 接收参数
            json_dict = json.loads(request.body.decode())
            email = json_dict.get('email')

            # 校验参数
            if not email:
                return http.JsonResponse({'code': 400,
                                          'errmsg': '缺少email参数'})
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400,
                                          'errmsg': '参数email有误'})

                # 赋值email字段
            try:
                request.user.email = email
                print(request.user)
                request.user.save()
            except Exception as e:
                logger.error(e)
                return http.JsonResponse({'code': 400, 'errmsg': '添加邮箱失败'})

            verify_url = generate_verify_email_url(request.user)
            send_verify_email(email, verify_url)
            return http.JsonResponse({'code': 0, 'errmsg': '添加邮箱成功'})


class VerifyEmailView(View):
    def get(self, request):
        # - 1.接收 token
        token = request.GET.get('token')

        if not token:
            return JsonResponse({'code': 400, 'errmsg': 'token缺少'})

        # - 2.解密
        data_dict = check_verify_email_token(token)
        # - 4.去数据库对比 user_id,email
        try:
            user = User.objects.get(pk=data_dict.id,email=data_dict.email)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '参数有误!'})

        # - 5.修改激活状态
        try:
            user.email_active = True
            user.save()
        except Exception as e:
            return JsonResponse({'code': 0, 'errmsg': '激活失败!'})



class AddressView(View):
    """用户收货地址"""

    def get(self, request):
        """提供地址管理界面
        """
        # 获取所有的地址:
        addresses = Address.objects.filter(user=request.user,
                                           is_deleted=False)

        # 创建空的列表
        address_dict_list = []
        # 遍历
        for address in addresses:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            }

            # 将默认地址移动到最前面
            default_address = request.user.default_address
            if default_address.id == address.id:
                # 查询集 addresses 没有 insert 方法
                address_dict_list.insert(0, address_dict)
            else:
                address_dict_list.append(address_dict)

        default_id = request.user.default_address_id

        return render(request, 'user_center_site.html',{'code': 0,'errmsg': 'ok','addresses': address_dict_list,'default_address_id': default_id})


class CreateAddressView(LoginRequiredJSONMixin, View):
    """新增地址"""

    def post(self, request):
        """实现新增地址逻辑"""
        # 判断是否超过地址上限：最多20个
        # Address.objects.filter(user=request.user).count()
        count = request.user.addresses.count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '超过地址数量上限'})

        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.HttpResponseBadRequest('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseBadRequest('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseBadRequest('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseBadRequest('参数email有误')

        # 保存地址信息
        try:
            address = Address.objects.create(
                user=request.user,
                title = receiver,
                receiver = receiver,
                province_id = province_id,
                city_id = city_id,
                district_id = district_id,
                place = place,
                mobile = mobile,
                tel = tel,
                email = email
            )

            # 设置默认地址
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '新增地址失败'})

        # 新增地址成功，将新增的地址响应给前端实现局部刷新
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应保存结果
        return JsonResponse({'code': 0, 'errmsg': '新增地址成功', 'address':address_dict})

class CreateAddressView(LoginRequiredJSONMixin, View):
        """新增地址"""

        def post(self, request):
            """实现新增地址逻辑"""
            # 判断是否超过地址上限：最多20个
            # Address.objects.filter(user=request.user).count()
            count = request.user.addresses.count()
            if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
                return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '超过地址数量上限'})

            # 接收参数
            json_dict = json.loads(request.body.decode())
            receiver = json_dict.get('receiver')
            province_id = json_dict.get('province_id')
            city_id = json_dict.get('city_id')
            district_id = json_dict.get('district_id')
            place = json_dict.get('place')
            mobile = json_dict.get('mobile')
            tel = json_dict.get('tel')
            email = json_dict.get('email')

            # 校验参数
            if not all([receiver, province_id, city_id, district_id, place, mobile]):
                return http.HttpResponseBadRequest('缺少必传参数')
            if not re.match(r'^1[3-9]\d{9}$', mobile):
                return http.HttpResponseBadRequest('参数mobile有误')
            if tel:
                if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                    return http.HttpResponseBadRequest('参数tel有误')
            if email:
                if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                    return http.HttpResponseBadRequest('参数email有误')

            # 保存地址信息
            try:
                address = Address.objects.create(
                    user=request.user,
                    title=receiver,
                    receiver=receiver,
                    province_id=province_id,
                    city_id=city_id,
                    district_id=district_id,
                    place=place,
                    mobile=mobile,
                    tel=tel,
                    email=email
                )

                # 设置默认地址
                if not request.user.default_address:
                    request.user.default_address = address
                    request.user.save()
            except Exception as e:
                logger.error(e)
                return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '新增地址失败'})

            # 新增地址成功，将新增的地址响应给前端实现局部刷新
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            }

            # 响应保存结果
            return JsonResponse({'code': 0, 'errmsg': '新增地址成功', 'address': address_dict})

class UpdateDestroyAddressView(LoginRequiredJSONMixin, View):
    """修改和删除地址"""

    def put(self, request, address_id):
        """修改地址"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})


        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.JsonResponse({'code': 400,
                                          'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400,
                                          'errmsg': '参数email有误'})

        # 判断地址是否存在,并更新地址信息
        try:
            Address.objects.filter(id=address_id).update(
                user = request.user,
                title = receiver,
                receiver = receiver,
                province_id = province_id,
                city_id = city_id,
                district_id = district_id,
                place = place,
                mobile = mobile,
                tel = tel,
                email = email
            )
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '更新地址失败'})

        # 构造响应数据
        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应更新地址结果
        return JsonResponse({'code': 0, 'errmsg': '更新地址成功', 'address': address_dict})

    def delete(self, request, address_id):
        """删除地址"""
        try:
            # 查询要删除的地址
            address = Address.objects.get(id=address_id)

            # 将地址逻辑删除设置为True
            address.is_deleted = True
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '删除地址失败'})

        # 响应删除地址结果
        return http.JsonResponse({'code': 0, 'errmsg': '删除地址成功'})




class DefaultAddressView(LoginRequiredJSONMixin, View):
    """设置默认地址"""

    def put(self, request, address_id):
        """设置默认地址"""
        try:
            # 接收参数,查询地址
            address = Address.objects.get(id=address_id)

            # 设置地址为默认地址
            request.user.default_address = address
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '设置默认地址失败'})

        # 响应设置默认地址结果
        return JsonResponse({'code': 0, 'errmsg': '设置默认地址成功'})


class PwdView(LoginRequiredMixin, View):
    def get(self, request):
        return render(request, 'user_center_pass.html')

    def post(self, request):
        # 接收
        old_pwd = request.POST.get('old_pwd')
        new_pwd = request.POST.get('new_pwd')
        new_cpwd = request.POST.get('new_cpwd')

        # 验证
        # 1.旧密码是否正确
        user = request.user
        if not user.check_password(old_pwd):
            return http.HttpResponseForbidden('旧密码错误')
        if not re.match('^[0-9A-Za-z]{8,20}$', new_pwd):
            return http.HttpResponseForbidden('密码为8-20个字符')
        # 确认密码
        if new_pwd != new_cpwd:
            return http.HttpResponseForbidden('两个密码不一致')

        # 处理
        user.set_password(new_pwd)
        user.save()

        # 响应
        return render(request, 'user_center_pass.html')